package cn.maka.web.servlet;

import cn.maka.dao.UserDAO;
import cn.maka.dao.impl.UserDaoImpl;
import cn.maka.domain.User;
import cn.maka.service.UserService;
import cn.maka.service.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");



        //System.out.println(parameterMap);

        String checkCodeJSP = request.getParameter("verifycode");

        HttpSession session = request.getSession();
        String checkCode = (String) session.getAttribute("checkCode");

        //System.out.println(checkCode);

        session.removeAttribute("checkCode");



        //System.out.println(loginUser);

        if (checkCodeJSP!=null && checkCodeJSP.equalsIgnoreCase(checkCode) ){
            Map<String, String[]> parameterMap = request.getParameterMap();

            User user = new User();
            try {
                BeanUtils.populate(user,parameterMap);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }


            UserService userService = new UserServiceImpl();
            User loginUser = userService.login(user);

            if (loginUser != null){
                session.setAttribute("user",loginUser);
                response.sendRedirect(request.getContextPath()+"/index.jsp");
            }else {
                request.setAttribute("error","用户名或密码错误");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
            }
        }else {
            request.setAttribute("error","验证码错误");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }



    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
